package com.fenfen.novel.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.XpPreferenceFragment;
import android.text.TextUtils;

import com.afollestad.materialdialogs.folderselector.FolderChooserDialog;
import com.fenfen.novel.BaseActivity;
import com.fenfen.novel.R;
import com.fenfen.novel.SettingActivity;
import com.fenfen.novel.utils.SharedPrefsUtils;

import net.xpece.android.support.preference.ColorPreference;

public class SettingFragment extends XpPreferenceFragment {
  private static Context context;
  private Preference downDirPref;

  public static SettingFragment newInstance(Bundle args) {
    SettingFragment fragment = new SettingFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override
  public void onCreatePreferences2(Bundle savedInstanceState, String rootKey) {
    context = getActivity();
    addPreferencesFromResource(R.xml.preferences);

    bindPreferenceSummaryToValue(findPreference("theme_color"));
    Preference navPreference = findPreference("navigation_color");
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
      navPreference.setVisible(false);
    } else {
      navPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {
          boolean isFollowTheme = (boolean) o;
          ((BaseActivity) context).notifyAllChangeNavigationColor(isFollowTheme);
          return true;
        }
      });
    }
    
    downDirPref = findPreference(SharedPrefsUtils.ShardPrefsKey.DOWNLOAD_DIR);
    bindPreferenceSummaryToValue(downDirPref);
    downDirPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
      @Override
      public boolean onPreferenceClick(Preference preference) {
        new FolderChooserDialog.Builder((SettingActivity) context)
            .chooseButton(R.string.choose)  // changes label of the choose button
            .initialPath(SharedPrefsUtils.getInstance(context).getDownloadDir())  // changes initial path, defaults to external storage directory
            .tag(preference.getKey())
            .show();
        return true;
      }
    });
  }
  
  public void callDownDirUpdate(Object newValue) {
    downDirPref.callChangeListener(newValue);
  }

  private static void bindPreferenceSummaryToValue(Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    // Trigger the listener immediately with the preference's
    // current value.
    final String key = preference.getKey();
    if (preference instanceof ColorPreference) {
      sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, ((ColorPreference) preference).getColor());
    }
    if (key.equals(SharedPrefsUtils.ShardPrefsKey.DOWNLOAD_DIR)) {
      sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, SharedPrefsUtils.getInstance(context).getDownloadDir());
    }
  }

  private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
      String stringValue = value.toString();

      if (preference instanceof ColorPreference) {
        ColorPreference colorPreference = (ColorPreference) preference;
        int color = (int) value;
//                String colorString = String.format("#%06X", 0xFFFFFF & color);
//                preference.setSummary(colorString);
        int index = colorPreference.findIndexOfValue(color);
        if (index < 0) {
          preference.setSummary(null);
        } else {
          final CharSequence name = colorPreference.getNameForColor(color);
          preference.setSummary(name);
        }
        ((BaseActivity) context).notifyAllChangeTheme();
      } else {
        if (TextUtils.isEmpty(stringValue)) {
          return true;
        }
        // For all other preferences, set the summary to the value's
        // simple string representation.
        preference.setSummary(stringValue);
      }
      return true;
    }
  };

}
